package com.hxq.wap.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hxq.wap.dao.UserDao;
import com.hxq.wap.entity.UserEntity;
import com.hxq.wap.service.UserService;

@Controller
@RequestMapping(value = "")
public class UserCtrl {
	@Autowired
	private UserService userService;
	// @Autowired
	// private UserDao userDao;

	@RequestMapping(value = "/wap/login.do")
	public String login() {
		// 返回字符串，实际就是返回一个页面，这个页面的路径等于springmvc-servlet.xml配置文件中的prefix+这里返回的值+suffix
		return "wap/login";
	}

	@RequestMapping(value = "/wap/doLogin.do")
	// @ResponseBody 这个注解是用来返回json格式数据的；添加这个注解，返回的就不是页面，而是json数据
	public ModelAndView doLogin(HttpServletRequest request, HttpSession session) {
		// 返回类型为ModelAndView，也是返回一个页面，但是可以把页面需要的数据放在ModelAndView的对象中
		ModelAndView m = new ModelAndView("wap/index");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		// 这里为了简便，省去参数是否为空是否合法的判断
		UserEntity userEntity = new UserEntity();
		userEntity.setId(4);
		userEntity.setUserName("m");
		userEntity.setPassword("123");
		userEntity.setRealName("mameng");
		userEntity.setAge(19);
		// userService.save(userEntity);

		Sort sort = new Sort(Direction.DESC, "id");
		List<UserEntity> list = userService.findAll(sort);
		System.out.println(list.toString());
		Long longs = userService.countByUserName(userName);
		System.out.println("longs=" + longs);
		// userService.findSearch(userEntity);
		// userService.updatePassword(userName, "1234");
		// userService.deleteByEgId(4);
		UserEntity user = userService.login(userName, password);
		if (user != null) {
			// 放入一个数据，在页面可以通过"${userName}"的形式取出来
			m.addObject("userName", user.getRealName());
		}
		// 为了简便，省略错误情况的处理。。。。

		// 分页DEMO:
//		Pageable pageable = new PageRequest(1, 2); // 第二页 每页2条记录
		 Pageable pageable = new PageRequest(1, 2,sort); // 第二页 每页2条记录，先排序后分页

		Page<UserEntity> page = userService.findAll(pageable);
		Iterator<UserEntity> iterator = page.iterator();
		while (iterator.hasNext()) {
			UserEntity user1 = iterator.next();

			System.out.println(user1.getId() + "---------" + user1.getUserName());
		}

		int totalPages = page.getTotalPages(); // 总的页数
		int number = page.getNumber(); // 当前也是
		long totalElements = page.getTotalElements(); // 总共的个数

		System.out.println(totalPages + "---------" + number + "--------" + totalElements);

		// 排序DEMO：
		Sort sort1 = new Sort("age");
		

		List<UserEntity> findAll = userService.findAll(sort1);

		Iterator<UserEntity> iterator1 = findAll.iterator();
		while (iterator1.hasNext()) {
			UserEntity user2 = iterator1.next();
			System.out.println(user2.toString());
		}
		
		 Map<String, String> map = new HashMap<String, String>();
		    map.put("name", "%a%");
		    map.put("userName", "ma");
		    map.put("password", "1234");
		    map.put("age", null);
		    Specification<UserEntity> specification = buildSpecification(map);
		    List<UserEntity> list1 = userService.findAll(specification);
		    for (UserEntity user1 : list1) {
		        System.out.println(user1.toString());
		    }
		return m;
	}
	/*
	 * 创建动态查询条件组合.
	 */
	private Specification<UserEntity> buildSpecification(final Map<String, String> searchParams) {
	    return new Specification<UserEntity>() {
			@Override
	        public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
	        	List<Predicate> list = new ArrayList<Predicate>();
	            Path<String> namePath = root.get("userName");
	            Path<String> password = root.get("password");
	            Path<String> age = root.get("age");
//	            query.where(cb.and(cb.like(namePath, searchParams.get("name")),cb.equal(password, searchParams.get("password"))));
//	            System.out.println("--"+searchParams.get("name"));
	        	
	        	 Set<Map.Entry<String, String>> entryseSet=searchParams.entrySet();  
	        	  for (Map.Entry<String, String> entry:entryseSet) {  
	        	   System.out.println(entry.getKey()+","+entry.getValue());
	        	   if(entry.getKey().equals("userName")&&searchParams.get("name")!=null&&!searchParams.get("name").equals("")) {
//	        		   Predicate p1 = cb.equal(namePath, entry.getValue());
	        		   Predicate p1 = cb.like(namePath, searchParams.get("name"));
	        		   list.add(p1);
	        	   }
	        	   if(entry.getKey().equals("password")&&searchParams.get("password")!=null&&!searchParams.get("password").equals("")) {
	        		   Predicate p2 = cb.equal(password, entry.getValue());
	        		   list.add(p2);
	        	   }
	        	   if(entry.getKey().equals("age")&&searchParams.get("age")!=null&&!searchParams.get("age").equals("")) {
	        		   Predicate p3 = cb.equal(age, entry.getValue());
	        		   list.add(p3);
	        	   }
	        	  } 
	        	  Predicate[] p = new Predicate[list.size()];
	        	  query.where(cb.and(list.toArray(p)));
	            return query.getRestriction();
	        }
	    };
	}
}
